iT邦幫忙

4

【JavaScript】解構賦值

  • 分享至 

  • xImage
  •  

【前言】
本系列為個人前端學習之路的學習筆記,在過往的學習過程中累積了很多筆記,如今想藉著IT邦幫忙這個平台做整理+再複習。
本系列標題一律以【】標示該篇文章主要涉及的內容,例如【JavaScript】、【Vue】等等。
若內容有誤,還麻煩各路大神不吝於點出問題,感激不敬。


什麼是解構賦值?

首先,解構賦值是ES6的新語法糖
【JavaScript】幾個語法糖中我們有提過一些語法糖
語法糖對語言的功能沒有影響,它們並不會影響運作,邏輯與原本JavaScript語法一樣,但可以更方便
既然解構賦值是語法糖,那它到底方便了些什麼呢?

過去要將陣列中的值取出來賦予到變數上,我們可能會這樣寫:

const colors = ["white", "black", "red"];
const firstColor = colors[0];
const secondColor = colors[1];
const thirdColor = colors[2];
console.log(firstColor,secondColor,thirdColor); //white black red

要一行一行的宣告變數然後賦值,解構賦值讓我們可以這樣寫:

const colors = ["white", "black", "red"];
const [firstColor,secondColor,thirdColor] = colors;
console.log(firstColor,secondColor,thirdColor); //white black red

簡單來說,解構賦值會將=右邊的資料鏡射到左方的變數上
在這個案例中,新變數就會分別對應陣列colors索引0 1 2的值

如果手癢將左邊寫成這樣也會跳過:

const colors = ["white", "black", "red"];
const [ ,secondColor,thirdColor] = colors;
console.log(secondColor,thirdColor); //black red

它會依照左方的排列順序,對應陣列中的值賦予上去
遇到空的就跳過
如果超過的話則會是undefined

const colors = ["white", "black"];
const [firstColor,secondColor,thirdColor] = colors;
console.log(firstColor,secondColor,thirdColor); //white black undefined

物件的解構賦值

過去我們將變數中的值取出來賦值到變數上可能會這樣寫:

const person = {
    name: "ming",
    age: 20
}
const age = person.age;
console.log(age); //20

現在有了解構賦值我們可以這樣寫:

const person = {
    name: "ming",
    age: 20
}
const {age} = person;
console.log(age); //20

使用const { 變數 } = 物件名稱,以這個案例為例,從person物件中將age這個屬性單獨取出來變成一個變數age
不過要注意的是,這裡是將物件內特定屬性取出來當作單一變數(因此也要物件中有該屬性才可以)

也可以解構賦值物件中的方法:

const person = {
    name: "ming",
    age: 20,
    fn: function(){}
}
const {fn} = person;
console.log(fn); //function(){}

要特別注意的是語法是const { 變數 } = 物件名稱
如果因為是函式而寫成const {fn()} = person;是錯誤的

解構也可以加入預設值:

const person = {
    name: "ming"
}
const {age = 20} = person;
console.log(age); //20

當物件內沒有變數名稱的屬性時,自動幫你在這個變數上賦予預設值


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
greenriver
iT邦研究生 5 級 ‧ 2022-03-31 08:42:06

雖然知道解構賦值,不過我很少使用。
沒想到這麼方便,感謝分享。
/images/emoticon/emoticon41.gif

我要留言

立即登入留言